package cn.bone.auth.security.base.filter;

import cn.bone.auth.security.base.component.RSAKeyProperties;
import cn.bone.auth.security.base.utils.JWTUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class TokenVerifyFilter extends BasicAuthenticationFilter {

    private RSAKeyProperties prop;

    public TokenVerifyFilter(AuthenticationManager authenticationManager, RSAKeyProperties prop) {
        super(authenticationManager);
        this.prop = prop;
    }

    /*过滤请求*/

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("Authorization");
        if(token==null || "".equals(token)){
            token = request.getParameter("Authorization");
        }

        if(token==null || "".equals(token)){

            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            PrintWriter writer = response.getWriter();
            JSONObject obj = new JSONObject();
            obj.put("code","102");
            obj.put("message","用户未登录");
            writer.write(obj.toJSONString());
            writer.flush();
            writer.close();
            chain.doFilter(request, response);
            return;
        }else {
            JWTUtil.JJWTPayload payload = JWTUtil.getInfoFormToken(token, prop.getPublicKey());

            UsernamePasswordAuthenticationToken authentication = null;
            if(payload!=null){

                List<SimpleGrantedAuthority> list = new ArrayList<>();
                if(payload.getTags()!=null && !"".equals(payload.getTags())){
                    String[] tagStr = payload.getTags().split(",");
                    for(String tag : tagStr){
                        list.add(new SimpleGrantedAuthority(tag));
                    }
                }
                authentication = new UsernamePasswordAuthenticationToken(payload.getUsername(),null,list);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                chain.doFilter(request,response);
            }
        }
    }
}
